package com.yanwq.sayhi.controller.comment.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.pulltorefreshview.view.PullToLoadListener;
import com.yanwq.pulltorefreshview.view.PullToRefreshLayout;
import com.yanwq.pulltorefreshview.view.PullToRefreshListView;
import com.yanwq.pulltorefreshview.view.PullToRefreshListener;
import com.yanwq.sayhi.R;
import com.yanwq.sayhi.base.BaseToolbarActivity;
import com.yanwq.sayhi.common.client.OkJsonArrayResponseCallback;
import com.yanwq.sayhi.common.client.OkJsonObjectResponseCallback;
import com.yanwq.sayhi.common.client.OkRequestParams;
import com.yanwq.sayhi.common.client.OkRestClient;
import com.yanwq.sayhi.controller.comment.adapter.CommentAdapter;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.dao.bean.Article;
import com.yanwq.sayhi.dao.bean.Comment;
import com.yanwq.sayhi.dao.bean.Reply;
import com.yanwq.sayhi.dao.bean.User;
import com.yanwq.sayhi.widget.InputDialog;
import com.yanwq.sayhi.widget.MToast;

import java.util.List;

import butterknife.BindView;

public class CommentListActivity extends BaseToolbarActivity {

    @BindView(R.id.comment_refresh)
    PullToRefreshLayout refreshLayout;
    @BindView(R.id.comment_list)
    PullToRefreshListView listView;
    @BindView(R.id.comment_add)
    ImageView mAddV;
    @BindView(R.id.comment_sofa)
    View mSofaV;
    CommentAdapter mAdapter;

    public Article mArticle;
    private int mPage;
    private int mSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_list);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_back, menu);
        return true;
    }

    @Override
    public void init() {
        mArticle = (Article) getIntent().getSerializableExtra("article");
        mAdapter = new CommentAdapter();
        mPage = 0;
        mSize = 20;
    }

    @Override
    public void initView() {
        mToolbar.setTitle("评论列表");

        mAddV = (ImageView) findViewById(R.id.comment_add);
        mSofaV = findViewById(R.id.comment_sofa);

        listView.setAdapter(mAdapter);

        refreshLayout.setPullToRefreshListener(new PullToRefreshListener() {
            @Override
            public void onRefresh() {
                refreshCommentList();
            }
        });

        refreshLayout.setPullToLoadListener(new PullToLoadListener() {
            @Override
            public void onLoad() {
                loadCommentList();
            }
        });

        mAddV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final InputDialog inputDialog = new InputDialog(CommentListActivity.this);
                inputDialog.setPrompt(String.format(getString(R.string.comment_article), mArticle.getUser().getNickname()));
                inputDialog.setOk(getString(R.string.send));
                inputDialog.setCancel(getString(R.string.forget_it));
                inputDialog.setOkListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sendComment(inputDialog.getContent());
                    }
                });
                inputDialog.show();
            }
        });

        autoRefresh();
    }

    public void autoRefresh() {
        post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.startRefresh();
            }
        });
    }

    private void refreshCommentList() {
        mPage = 0;
        OkRequestParams params = new OkRequestParams();
        params.put("page", mPage);
        params.put("size", mSize);
        params.put("articleId", mArticle.getId());
        OkRestClient.getInstance().get(this,
                "/comment/list",
                params,
                new OkJsonArrayResponseCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(JSONArray jsonArray) {
                        List<Comment> commentList = JSON.parseArray(jsonArray.toJSONString(),
                                Comment.class);
                        mAdapter.refresh(commentList);

                        if (commentList.size() == 0) {
                            mSofaV.setVisibility(View.VISIBLE);
                        } else {
                            mSofaV.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onStop() {
                        refreshLayout.stopRefresh();
                    }
                });
    }

    private void loadCommentList() {
        mPage++;
        OkRequestParams params = new OkRequestParams();
        params.put("page", mPage);
        params.put("size", mSize);
        params.put("articleId", mArticle.getId());
        OkRestClient.getInstance().get(this,
                "/comment/list/",
                params,
                new OkJsonArrayResponseCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(JSONArray jsonArray) {
                        List<Comment> commentList = JSON.parseArray(jsonArray.toJSONString(),
                                Comment.class);
                        mAdapter.load(commentList);
                    }

                    @Override
                    public void onStop() {
                        refreshLayout.stopLoad();
                    }
                });
    }

    private void sendComment(String content) {
        if (TextUtils.isEmpty(content)) {
            return;
        }

        final Comment comment = new Comment();
        comment.setUser(UserMgr.get());
        comment.setArticle(mArticle);
        comment.setContent(content);
        OkRestClient.getInstance().post(this,
                "/comment/add",
                comment,
                new OkJsonObjectResponseCallback() {
                    @Override
                    public void onStart() {
                        showProgressDialog("正在发表言论");
                    }

                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        autoRefresh();
                    }

                    @Override
                    public void onStop() {
                        cancelProgressDialog();
                    }
                });
    }

    public void sendReply(String content, Comment comment, User toUser) {
        if (TextUtils.isEmpty(content)) {
            MToast.showShort(this, "吐槽内容不能为空");
            return;
        }

        final Reply reply = new Reply();

        if (comment != null) {
            reply.setComment(comment);
        }

        reply.setFromUser(UserMgr.get());

        if (toUser != null) {
            try {
                reply.setToUser(toUser.clone());
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        }

        reply.setContent(content);
        reply.getComment().setReplies(null);
        OkRestClient.getInstance().post(this,
                "/reply/add",
                reply,
                new OkJsonObjectResponseCallback() {
                    @Override
                    public void onStart() {
                        showProgressDialog("正在发表言论");
                    }

                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        autoRefresh();
                    }

                    @Override
                    public void onStop() {
                        cancelProgressDialog();
                    }
                });
    }
}
